<script>
	var commonCounter = 0;
	var totalPrice = 0;
	var itemCode = {}, itemName = {}, batchDate = {}, unitPrice = {}, txtFieldVal = {}, objCounter = {}, newStockQnt = {}, tempStockQnt = {}, splitQuantity = {}, cartFieldVal = {};
	function addToCart(i){
		itemCode['itemcode' + i] = $('#itemCode'+i).text();
		itemName['itemname' + i] = $('#itemName'+i).text();
		batchDate['batchdate' + i] = $("#batchDate"+i).text();
		unitPrice['unitprice' + i] = parseFloat($("#unitPrice"+i).text());
		txtFieldVal['txtfieldval'+i] = parseFloat($("#quantity"+i).val());
		$("#quantity"+i).val('');
		
		if(!objCounter['objcounter'+i]){
			splitQuantity['splitquantity' + i] = ($("#stockQnt"+i).text()).split(" ");
			newStockQnt['newstockqnt' + i] = parseFloat(splitQuantity['splitquantity' + i][0]);
			tempStockQnt['tempstockqnt' + i] = newStockQnt['newstockqnt' + i];
			if(tempStockQnt['tempstockqnt' + i] >= txtFieldVal['txtfieldval'+i])
				newStockQnt['newstockqnt' + i] = newStockQnt['newstockqnt' + i] - txtFieldVal['txtfieldval'+i];
			objCounter['objcounter' + i] = 1;
			$("#stockQnt"+i).text(newStockQnt['newstockqnt' + i] + " " +splitQuantity['splitquantity' + i][1]);
		}
		else{
			tempStockQnt['tempstockqnt' + i] = newStockQnt['newstockqnt' + i];
			if(tempStockQnt['tempstockqnt' + i] >= txtFieldVal['txtfieldval'+i])
				newStockQnt['newstockqnt' + i] = newStockQnt['newstockqnt' + i] - txtFieldVal['txtfieldval'+i];
			$("#stockQnt"+i).text(newStockQnt['newstockqnt' + i] + " " + splitQuantity['splitquantity' + i][1]);
		}
		
		if(txtFieldVal['txtfieldval'+i] == 0){
			$("#messages").html("<div id='msg1' title='Indika Stores'>You should enter a quantity</div>");
			$( "#msg1" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}else if(!txtFieldVal['txtfieldval'+i]){
			$("#messages").html("<div id='msg2' title='Indika Stores'>You should enter a quantity</div>");
			$( "#msg2" ).dialog({ buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}else{
			if(tempStockQnt['tempstockqnt' + i] < txtFieldVal['txtfieldval'+i]){
				$("#messages").html("<div id='msg3' title='Indika Stores'>Available quantity is not sufficient for your request</div>");
				$( "#msg3" ).dialog({ buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
			}
			else{
				if(commonCounter == 0){
					var newRow = $(	"<tr><th>Item Name</th><th>Quantity</th><th>Amount</th><th>Delete</th></tr>");
					$('table.cart').append(newRow);
				}
				if(objCounter['objcounter' + i] > 1){
					cartFieldVal['cartfieldval'+i] = parseFloat($("#displayCart input[type=text].cartQty"+i).val()) + txtFieldVal['txtfieldval'+i];
					$("#displayCart input[type=text].cartQty"+i).val(cartFieldVal['cartfieldval'+i]);
					$("#displayCart #amount"+i).text(cartFieldVal['cartfieldval'+i] * unitPrice['unitprice' + i]+" Rs");
				}else{
					$("#displayCart #title").text("Cart Content");
					cartFieldVal['cartfieldval'+i] = txtFieldVal['txtfieldval'+i];
					var newRow = $( "<tr id='row"+i+"'><td><input type='hidden' value='"+itemCode['itemcode' + i]+"' name='itemcode"+i+"'/>"+itemName['itemname' + i]+" </td>"+
										"<td><input type='hidden' value='"+unitPrice['unitprice' + i]+"' name='unitprice"+i+"'/><input type='text' size='6' value='"+cartFieldVal['cartfieldval'+i]+"' class='cartQty"+i+"' name='quantity"+i+"' onkeydown='validateTxt(); testForEnter();' onChange='updateQty("+i+")'/></td>"+
										"<td><input type='hidden' value='"+batchDate['batchdate' + i]+"' name='batchdate"+i+"'/><div id='amount"+i+"'></div></td>"+
										"<td><button type='button' id='deleteBtn' onClick='deleteRow("+i+")'></button></td>"+
									"</tr>");
					$('table.cart').append(newRow);
					$("#displayCart #amount"+i).text(cartFieldVal['cartfieldval'+i] * unitPrice['unitprice' + i]+" Rs");
					objCounter['objcounter' + i]++;
					commonCounter++;
				}
				if(commonCounter > 0){
					$("#finish").html("<button id='submitBtn' type='submit'><img src='public/images/button-img/finish.png'/><span> Finish order </span></button>");
					totalPrice = totalPrice + (unitPrice['unitprice' + i] * txtFieldVal['txtfieldval'+i]);
					$("#total").text("Total Price : "+totalPrice+" Rs/=");
					$("#displayCart #hidden").html("<td><input type='hidden' value='"+totalPrice+"' name='totalprice' /></td>");
					$("#payment").html( "<td>Cash: <input id='custPayment' type='text' onkeydown='validateTxt(); testForEnter();'/></td>"+
										"<td><button type='button' id='opener'  onclick='getBalance()'><img src='public/images/button-img/balance.png'/><span>Balance </span></button></td>");
				}
			}
		}
		dTable.fnFilter('');
	}

	function validateTxt() {
		// Allow: backspace, delete, tab, escape, enter and .
		if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || event.keyCode == 190 || event.keyCode == 110 || 
			 // Allow: Ctrl+A
			(event.keyCode == 65 && event.ctrlKey === true) || 
			 // Allow: home, end, left, right
			(event.keyCode >= 35 && event.keyCode <= 39)) {
				 // let it happen, don't do anything
				 return;
		}
		else {
			if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
				event.preventDefault(); 
			}   
		}
	}

	function testForEnter() {
		if (event.keyCode == 13) {        
			event.cancelBubble = true;
			event.returnValue = false;
		}
	}

	function updateQty(i){
		var temp = {}, startedStockQty = {};
		temp['temp'+i] = newStockQnt['newstockqnt' + i];
		startedStockQty['startedstockqty'+i] = parseFloat(splitQuantity['splitquantity' + i][0]);
		cartFieldVal['cartfieldval'+i] = parseFloat($("#displayCart input[type=text].cartQty"+i).val());
		if(cartFieldVal['cartfieldval'+i] > startedStockQty['startedstockqty'+i]){
			$("#messages").html("<div id='msg4' title='Indika Stores'>Available quantity is not enough.");
			$( "#msg4" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
			cartFieldVal['cartfieldval'+i] = startedStockQty['startedstockqty'+i] - temp['temp'+i];
			$("#displayCart input[type=text].cartQty"+i).val(cartFieldVal['cartfieldval'+i]);
		}
		else{
			newStockQnt['newstockqnt' + i] = startedStockQty['startedstockqty'+i] - cartFieldVal['cartfieldval'+i];
			$("#stockQnt"+i).text(newStockQnt['newstockqnt' + i] + " " + splitQuantity['splitquantity' + i][1]);
			$("#displayCart #amount"+i).text(cartFieldVal['cartfieldval'+i] * unitPrice['unitprice' + i]+" Rs");
			totalPrice = totalPrice + (unitPrice['unitprice' + i] * (temp['temp'+i] - newStockQnt['newstockqnt' + i]));
			$("#total").text("Total Price : "+totalPrice+" Rs/=");
			$("#displayCart #hidden").html("<td><input type='hidden' value='"+totalPrice+"' name='totalprice' /></td>");
			$("#finish").html("<button id='submitBtn' type='submit'><img src='public/images/button-img/finish.png'/><span> Finish order </span></button>");
		}
			
	}

	function deleteRow(i) {
		$("#stockQnt"+i).text(splitQuantity['splitquantity' + i][0] + " " + splitQuantity['splitquantity' + i][1]);
		objCounter['objcounter' + i] = 1;
		totalPrice = totalPrice - (unitPrice['unitprice' + i] * cartFieldVal['cartfieldval'+i]);
		newStockQnt['newstockqnt' + i] = parseFloat(splitQuantity['splitquantity' + i][0]);
		$("#total").text("Total Price : "+totalPrice+" Rs/=");
		$("#displayCart #hidden").html("<td><input type='hidden' value='"+totalPrice+"' name='totalprice' /></td>");
		$("#finish").html("<button id='submitBtn' type='submit'><img src='public/images/button-img/finish.png'/><span> Finish order </span></button>");
		$("#row"+i).remove();
	}

	function getBalance(){
		var balance = parseFloat($("#payment #custPayment").val()) - totalPrice;
		if(balance >= 0)
			$("#balance").text("Balance : "+balance+" Rs/=");
		else{
			$("#payment #custPayment").val('');
			$("#messages").html("<div id='msg5' title='Indika Stores'>Selling price should be greater than total price.</div>");
			$( "#msg5" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 470 });
		}
	}
</script>

<div id="home">
	<div id="cartTable">
		<?php
			if (!isset($_SESSION)) {
				 session_start();
			}
			include("./system/dbconnection.php");
			if($result = mysql_query("SELECT items.itemCode, items.itemName, categories.categoryName, batches.batchDate, stock.unitPrice, stock.EXP, stock.stockQuantity, units.unitCode FROM  `stock` INNER JOIN  `items` ON stock.itemCode = items.itemCode INNER JOIN `categories` ON items.categoryId = categories.categoryId INNER JOIN  `batches` ON stock.batchId = batches.batchId INNER JOIN  `units` ON items.itemUnit = units.unitId WHERE stock.stockQuantity != 0")){
				$num = mysql_num_rows($result);
				if(mysql_query("DELETE FROM stock WHERE stockQuantity = 0")){
				}else{
					$_SESSION['error'] = "Error occured ";
				}
				$_SESSION['num'] =  $num;
			}else{
				$_SESSION['error'] = "Error occured ";
			}
			if(isset($_SESSION['success']) && $_SESSION['success'] != "") {  
				echo '<div id="success" title="Indika Stores">'.$_SESSION['success'].'</div>';
				echo '<script type=\'text/javascript\'>';
				echo '$( "#success" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 400 });';  
				echo '</script>';   
			}else if(isset($_SESSION['error']) && $_SESSION['error'] != "") {  
				echo '<div id="error" title="Indika Stores">'.$_SESSION['error'].'</div>';
				echo '<script type=\'text/javascript\'>';
				echo '$( "#error" ).dialog({buttons: { "Ok": function() { $(this).dialog("close"); } }, draggable: true, hide: "slide", show: "slide", width: 450 });';  
				echo '</script>';  
			}  
		?>
		<table border="1" cellpadding="2" class="stockTable dataTable" style="width:100%">
			<thead>
				<tr>
					<th>Item Code</th>
					<th>Item Name</th>
					<th>Category</th>
					<th>Batch Date</th>
					<th>Unit Price</th>
					<th>Available</th>
					<th>Required</th>
					<th>Add</th>
				</tr>
			</thead>
			<tbody>
			<?php
				$i=0;
				while ($i < $num) {
					$f1=mysql_result($result,$i,"itemCode");
					$f2=mysql_result($result,$i,"itemName");
					$f3=mysql_result($result,$i,"categoryName");
					$f4=mysql_result($result,$i,"batchDate");
					$f5=mysql_result($result,$i,"unitPrice");
					$f6=mysql_result($result,$i,"stockQuantity");
					$f7=mysql_result($result,$i,"unitCode");
			?>
				<tr>
					<td id="itemCode<?php echo $i ?>"><?php echo $f1; ?></td>
					<td id="itemName<?php echo $i ?>"><?php echo $f2; ?></td>
					<td id="itemName<?php echo $i ?>"><?php echo $f3; ?></td>
					<td id="batchDate<?php echo $i ?>"><?php echo $f4; ?></td>
					<td id="unitPrice<?php echo $i ?>"><?php echo $f5; ?></td>
					<td id="stockQnt<?php echo $i ?>"><?php echo $f6. ' ' .$f7 ?></td>
					<td><input type="text" size="5" class="quantity" id="quantity<?php echo $i ?>" onkeydown="validateTxt(); if (event.keyCode == 13) document.getElementById('addBtn<?php echo $i ?>').click()"/></td>
					<td id='add'><button type="submit" id="addBtn<?php echo $i ?>" onclick="addToCart(<?php echo $i ?>);" ><img src="public/images/button-img/add.png"/><span> Add </span></button></td>
				</tr>
			<?php
					$i++;
				}
			?>
			</tbody>
		</table>
		<div id="messages"></div>
	</div>
	<div id='form'>
		<form action='./system/action/addOrders.php' method='post'>
			<div id="displayCart">
				<div id="title">Shopping cart is empty</div>
				<table id="cart" border="1" cellpadding="2" cellspacing="0" class="cart" style="text-align: center"></table>
				<div id="hidden"></div>
			</div>
			<div id='bill'>
				<div id="total"></div>
				<div id="payment"></div>
				<div id="balance"></div>
				<div id="finish"></div>
			</div>
		</form>
	</div>
</div>